package xyz.ibenben.zhongdian.system.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import xyz.ibenben.zhongdian.common.annotation.SystemServiceLog;
import xyz.ibenben.zhongdian.common.shiro.PasswordHelper;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.sys.SysUserForm;
import xyz.ibenben.zhongdian.system.mapper.sys.SysUserMapper;
import xyz.ibenben.zhongdian.system.service.sys.SysUserService;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 系统用户服务实现类
 * 系统级用户所使用的，是权限系统中的一部分
 * 提供了一些基本的服务，如根据用户名称查询用户信息列表、根据站内信类型获取用户等方法。
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * selectByUsername用户记录
     *
     * @param username 参数
     * @return 返回值
     */
    @Override
    @SystemServiceLog(description = "selectByUsername用户记录")
    public SysUser selectByUsername(String username) {
        List<SysUser> userList = sysUserMapper.selectList(getExample(null, username, null));
        if (!userList.isEmpty()) {
            return userList.get(0);
        }
        return null;
    }

    /**
     * save用户记录
     *
     * @param entity 参数
     * @return 返回值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemServiceLog(description = "save用户记录")
    public boolean save(SysUser entity) {
        PasswordHelper passwordHelper = new PasswordHelper();
        passwordHelper.encryptPassword(entity);
        //此时没有用户主键需要保存后拿到此主键再更新记录的时间和操作人
        return sysUserMapper.insert(entity) > 0;
    }

    /**
     * delete用户记录
     *
     * @param key 参数
     * @return 返回值
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @SystemServiceLog(description = "delete用户记录")
    public int delete(Object key) {
        int result = 0;
        //删除用户角色表
        int resultUR = sysUserMapper.deleteUserRoleById(key);

        //删除用户表
        SysUser entity = this.getById((Serializable) key);
        entity.setDelFlag(1);
        entity.setDelId((Long) SecurityUtils.getSubject().getSession().getAttribute("currentUserId"));
        entity.setDelTime(new Date());
        int resultU = sysUserMapper.updateById(entity);
        //关系表为物理删除，用户表为逻辑删除
        //当都不为0时才能返回用户返回的数字
        if (resultUR != 0 && resultU != 0) {
            result = resultU;
        }
        return result;
    }

    /**
     * findByType用户记录
     *
     * @param ordinal 参数
     * @return 返回值
     */
    @Override
    @SystemServiceLog(description = "findByType用户记录")
    public List<SysUser> findByType(int ordinal) {
        return sysUserMapper.selectList(getExample(null, null, ordinal));
    }

    /**
     * checkExsit用户记录
     *
     * @param email    参数
     * @param username 参数
     * @return 返回值
     */
    @Override
    @SystemServiceLog(description = "checkExist用户记录")
    public SysUser checkExist(String email, String username) {
        List<SysUser> list = sysUserMapper.selectList(getExample(email, username, null));
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据各种条件去查询
     *
     * @param email    邮箱
     * @param username 用户名称
     * @param ordinal  类型
     * @return 条件实例
     */
    private QueryWrapper<SysUser> getExample(String email, String username, Integer ordinal) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(email)) {
            wrapper.eq("email", email);
        }
        if (StringUtils.isNotBlank(username)) {
            wrapper.eq("username", username);
        }
        if (null != ordinal) {
            wrapper.eq("type", ordinal);
        }
        return wrapper;
    }

    @Override
    public IPage<SysUser> findAll(Page<SysUser> page, SysUserForm sysUserForm) {
        return sysUserMapper.findAll(page, sysUserForm);
    }

    @Override
    public SysUser findByKey(Long id) {
        return sysUserMapper.findByKey(id);
    }

    @Override
    public SysUser selectUserWithRoleByUsername(String username) {
        return sysUserMapper.selectUserWithRoleByUsername(username);
    }

}
